import 'package:basic_common/app_theme.dart';
import 'package:basic_common/common_exports.dart';
import 'package:basic_patient/patient_controller.dart';
import 'package:basic_widgets/app_bar_widget.dart';
import 'package:basic_widgets/image_widget.dart';
import 'package:basic_widgets/input_widget.dart';
import 'package:basic_widgets/text_widget.dart';

class PatientPage extends GetView<PatientController> {
  ItemScrollController? itemScrollController = ItemScrollController();
  ItemPositionsListener itemPositionsListener = ItemPositionsListener.create();
final controller=Get.put(PatientController());
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: mainAppbar(title: "患者"),
      body: GetBuilder<PatientController>(
        id: 'patientInfo',
        builder: (controller) => Stack(
          children: [
            Column(
              children: [
                GestureDetector(
                  onTap: () {
                    Get.toNamed(AppRoutes.patientSearch);
                  },
                  child: searchBox(
                    searchController: controller.searchController,
                    onSubmitted: (value) {},
                  ),
                ),
                // buildHeadItemWidget(
                //     icon: "assets/patient/icon_attend.svg", text: "已关注"),

                controller.patientList.isEmpty
                    ? EmptyBox(
                        title: "暂无患者",
                      )
                    : _buildListWidget(),
              ],
            ),
            Positioned(
              width: ScreenHelper.width(40),
              height: ScreenHelper.width(540),
              right: 0,
              top: 200,
              child: Listener(
                // 手指按下触发
                onPointerDown: (PointerDownEvent e) {
                  //打印手指按下的位置(相对于屏幕)
                  int i = e.localPosition.dy ~/ 21;
                  controller.changeIndex(i);
                  itemScrollController!.jumpTo(index: i);
                },
                // 手指滑动时触发
                onPointerMove: (PointerMoveEvent e) {
                  //用户手指滑动时，更新偏移
                  int i = e.localPosition.dy ~/ 21;

                  if (i >= 0 && i <= controller.az.length - 1) {
                    if (i != controller.state.currentIndex) {
                      controller.changeIndex(i);
                    }
                  }
                },
                child: ListView.builder(
                  padding: const EdgeInsets.all(0),
                  itemCount: controller.dataList.length,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) {
                    return SizedBox(
                      height: ScreenHelper.width(20),
                      child: Container(
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            // borderRadius: BorderRadius.circular(20),
                            color: controller.state.currentIndex == index
                                ? const Color(0xffF3F4F7)
                                : null,
                            shape: BoxShape.circle),
                        child: controller.dataList[index].label == '*'
                            ? Container(
                                width: ScreenHelper.width(8),
                                height: ScreenHelper.width(8),
                                decoration: BoxDecoration(
                                    color:
                                        controller.state.currentIndex == index
                                            ? const Color(0xffFFCF57)
                                            : const Color(0xff9299A0),
                                    borderRadius: BorderRadius.circular(20)),
                              )
                            : Text(
                                controller.dataList[index].label,
                                style: TextStyle(
                                  fontFamily: 'sansBold',
                                  color: controller.state.currentIndex == index
                                      ? AppTheme.primyColor
                                      : const Color(0xff9299A0),
                                ),
                              ),
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildHeadItemWidget({required String icon, required String text,double width=16}) {
    return Container(
      color: Colors.white,
      child: ListTile(
        titleAlignment: ListTileTitleAlignment.threeLine,
        // leading: SvgPicture.asset(
        //   icon,
        //   width: ScreenHelper.width(30),
        // ),
        leading: svgImage(assets: icon, package: "basic_common",width:width),
        minLeadingWidth: ScreenHelper.width(10),
        title: Text(
          text,
          style: TextStyle(color: AppTheme.dartTextColor),
        ),
      ),
    );
  }

  Widget _buildListWidget() {
    return Expanded(
      child: GetBuilder<PatientController>(
        id: 'patientInfo',
        builder: (logic) {
          return SizedBox(
            height: controller.dataList.length * 190,
            child: Stack(
              children: [
                const SizedBox(
                  height: 160,
                ),
                Listener(
                    onPointerUp: (e) {
                      // 拉动列表，取消右侧索引
                      logic.changeIndex(-1);
                    },
                    child: ScrollablePositionedList.builder(
                        physics: const BouncingScrollPhysics(),
                        itemScrollController: itemScrollController,
                        itemPositionsListener: itemPositionsListener,
                        padding: const EdgeInsets.all(0),
                        itemBuilder: (context, index) {
                          return
                           index == 0
                              ? Column(
                                  children: [
                                    GestureDetector(
                                      onTap: () => Get.toNamed(
                                          AppRoutes.emptyPage,
                                          arguments: {'title': "已关注"}),
                                      child: buildHeadItemWidget(
                                          icon:
                                              "assets/patient/icon_attend.svg",
                                          text: "已关注",width:30),
                                    ),
                                    GestureDetector(
                                      onTap: () => Get.toNamed(
                                          AppRoutes.emptyPage,
                                          arguments: {'title': "已签约"}),
                                      child: buildHeadItemWidget(
                                          icon: "assets/patient/icon_sign.svg",
                                          text: "已签约患者",width:30),
                                    ),
                                    // buildHeadItemWidget(
                                    //     icon: "assets/patient/icon_tag.svg",
                                    //     text: "标签"),
                                  ],
                                )
                              : 
                              ListItem(
                                  logic: logic,
                                  index: index - 1,
                                );
                        },
                        itemCount: logic.dataList.length + 1,
                      )),
              ],
            ),
          );
        },
      ),
    );
  }
}

class ListItem extends StatelessWidget {
  PatientController logic;
  int index;
  ListItem({super.key, required this.logic, required this.index});
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          padding: const EdgeInsetsDirectional.only(start: 10),
          color: Colors.grey.shade200,
          height: 30,
          width: double.infinity,
          alignment: Alignment.centerLeft,
          child: Text(
            logic.dataList[index].label,
            style: TextStyle(color: AppTheme.dartWeakTextColor),
          ),
        ),
        GetBuilder<PatientController>(
          id: 'patientInfo',
          builder: (controller) => Container(
            padding: const EdgeInsetsDirectional.only(start: 15),
            // height: ScreenHelper.height((logic
            //                         .dataList[index].children.length)*90.0),
            child: ListView.builder(
                // 禁用滑动事件
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                padding: const EdgeInsets.all(0),
                itemBuilder: (context, cityIndex) {
                  return InkWell(
                    child: SizedBox(
                      height: ScreenHelper.height(90),
                      child: Column(
                        children: [
                          Expanded(
                            // child: Container(
                            //   alignment: Alignment.centerLeft,
                            //   child:
                            //       Text(logic.dataList[index].children[cityIndex]),
                            // ),
                            child: buildListItem(
                                itemData: logic
                                    .dataList[index].children[cityIndex]),
                          ),
                          const Divider(
                            height: 0.5,
                          )
                        ],
                      ),
                    ),
                    onTap: () {
                      Get.toNamed(AppRoutes.patientDetail, arguments: {
                        "consumerNo": logic
                            .dataList[index].children[cityIndex].consumerNo
                      });
                    },
                  );
                },
                itemCount: logic.dataList[index].children.length),
          ),
        )
      ],
    );
  }

  Widget buildListItem({required dynamic itemData}) {
    return Padding(
      padding: EdgeInsets.only(top: ScreenHelper.height(10)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          circleImg(
              width: ScreenHelper.width(52),
              head: itemData.patitentAvatarUrl ?? ''),
          SizedBox(
            width: ScreenHelper.width(10),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    itemData.nickName ?? '',
                    style: TextStyle(
                        fontSize: ScreenHelper.sp(18),
                        color: AppTheme.dartTextColor),
                  ),
                  SizedBox(
                    width: ScreenHelper.width(10),
                  ),
                  Text(
                      "${itemData.age != null ? itemData.age.toInt().toString() : 0}岁"),
                  SizedBox(
                    width: ScreenHelper.width(10),
                  ),
                  Image.asset(
                    itemData.gender == '1'
                        ? "assets/profile/icon_sex_male.png"
                        : 'assets/profile/icon_female.png',
                    width: ScreenHelper.width(14),
                    height: ScreenHelper.width(14),
                    package: "basic_common",
                  ),
                ],
              ),
              SizedBox(
                height: ScreenHelper.height(15),
              ),
              Container(
                width: ScreenHelper.width(200),
                height: ScreenHelper.height(24),
                child: Text(
                  itemData.labelName ?? "",
                  style: TextStyle(
                      color: AppTheme.weakTextColor,
                      fontSize: ScreenHelper.sp(14)),
                ),
                // child: ListView(
                //   scrollDirection: Axis.horizontal,
                //   children: buildIdenity(tagStr: itemData.tagsFromDoctor ?? ''),
                // ),
              )
            ],
          )
        ],
      ),
    );
  }

  /// 医生身份标签项
  List<Widget> buildIdenity({required String tagStr}) {
    List<Widget> tagWidgetList = [];
    if (tagStr.contains(',')) {
      List<String> tagList = tagStr.split(',');
      tagList.forEach((element) {
        tagWidgetList.add(tagItem(element));
      });
    }
    return tagWidgetList;
  }

  Widget tagItem(String tag) {
    return Container(
      alignment: Alignment.center,
      width: ScreenHelper.width(50),
      height: ScreenHelper.height(24),
      margin: EdgeInsets.symmetric(horizontal: ScreenHelper.width(4)),
      decoration: BoxDecoration(
          border: Border.all(color: AppTheme.primyColor),
          borderRadius: BorderRadius.circular(6)),
      child: Text(
        tag,
        style: TextStyle(
            color: AppTheme.primyColor, fontSize: ScreenHelper.sp(12)),
      ),
    );
  }

  /// tagzhi
}
